package com.nb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nb.dao.DishDao;
import com.nb.domain.Dish;
import com.nb.domain.DishFlavor;
import com.nb.dto.DishDto;
import com.nb.service.DishFlavorService;
import com.nb.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;


    @Override
    public void saveWithFlavor(@RequestBody DishDto dishDto) {
            ///保存基本菜品信息
            this.save(dishDto);

            Long dishId = dishDto.getId();

            List<DishFlavor> flavorList = dishDto.getFlavors();

            flavorList.stream().map((item) ->{
                item.setDishId(dishId);
                return item;
            }).collect(Collectors.toList());

            dishFlavorService.saveBatch(flavorList);
    }

    @Override
    public DishDto getFlavorById(Long id) {

        //根据传入的id查询该对象
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        //拷贝对象，将dish对象的数据拷贝给dishdto对象
        BeanUtils.copyProperties(dish,dishDto);

        //查询器
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        //
        lqw.eq(DishFlavor::getDishId,dish.getId());

        List<DishFlavor> list = dishFlavorService.list(lqw);

        dishDto.setFlavors(list);

        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新基本信息
        this.updateById(dishDto);
    //更新口味信息
        //更新口味前先删除旧口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lqw);
        //更新新口味
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }







}
